import Taro, {Component} from '@tarojs/taro'
import {View, Image, Text, ScrollView} from '@tarojs/components'
import {connect} from '@tarojs/redux'
import * as homeActions from '../../actions/home'
// import { AtNoticebar } from 'taro-ui'
import Fix from '../../components/Fix'
// import Navbar from '../../components/Navbar'
import {getNavSize} from '../../utils/style'
import classNames from 'classnames'
// import yijia from '../../assets/img/home/yijia.png'
// import Menu from '../../components/Menu'
// parseTime
import {formatZero, strToDate} from '../../utils/comman'
import fetch from '../../utils/request'
import {API_GOODS_CATE} from '../../constants/api'
import MySwiper from '../../components/Swiper'
import './index.scss'


const reg1 = /\r\n/g //匹配回车1
const reg2 = /\n/g //匹配回车2


let page = 1
let fetchState = 'init'

@connect(state => ({...state.home}), {...homeActions})
class Home extends Component {

  config = {
    // navigationBarTitleText: '阳光、碎片',
    // 定义需要引入的第三方组件
    usingComponents: {
      'add-tips': '../../wxComponents/weplug-add-tips-master', // 书写第三方组件的相对路径
      // "lottie": "../../wxComponents/lottie-miniapp/component/lottie"
      // 'my-swiper':'../../wxComponents/wxapp-swiper/components/theSwiper',
      'i-spin': '../../wxComponents/spin/index'
    },
    enablePullDownRefresh: false,
    navigationStyle: "custom"
  }


  static options = {
    addGlobalClass: true,
  }

  static defaultProps = {
    topHeight: 0,
  };

  state = {
    loading: true,
    month: new Date().toDateString().split(" ")[1],
    day: new Date().getDate(),
    week: this.getMyDay(new Date()),
    navHeight: 0,
    categories: [],
    cateIds: '',
    isfixed: false,
    tabHeight: 0,
    scrollIntoView: 'top',
    page: 1
  }

  getMyDay(date) {
    var week;
    if (date.getDay() == 0) week = "周日";
    if (date.getDay() == 1) week = "周一";
    if (date.getDay() == 2) week = "周二";
    if (date.getDay() == 3) week = "周三";
    if (date.getDay() == 4) week = "周四";
    if (date.getDay() == 5) week = "周五";
    if (date.getDay() == 6) week = "周六";
    return week;
  }

  seeShoucang() {
    const token = Taro.getStorageSync('token')
    if (!token) {
      Taro.navigateTo({
        url: `/pages/auth/index?redirect=/pages/like/index`
      })
    } else {
      Taro.navigateTo({
        url: `/pages/like/index`
      })
    }
  }

  async getCates() {
    let cates = await fetch({
      url: API_GOODS_CATE,
      payload: {}
    })
    cates = [{name: '全部', id: '', active: true}, ...cates]
    this.setState({
      categories: cates.map((item, index) => {
        item.active = index == 0
        return item
      })
    }, () => {
      Taro.nextTick(() => {
        Taro.createSelectorQuery().in(this.$scope).select('#home-tabs').boundingClientRect(rect => { //获取元素1距离页面顶部高度
          this.setState({
            tabHeight: rect ? rect.height : 0
          })
        }).exec()
      })
    })
  }


  onShareAppMessage() {

  }

  async onPullDownRefresh() {
    console.log('刷新')
    this.getList()
  }


  componentWillReceiveProps(nextProps) {
    if (nextProps.pullDown === true && this.props.pullDown != nextProps.pullDown && this.props.tabIndex == 0) {
      //切换了menuItem
      this.getList()
    }
  }


  componentDidMount() {
    // initLottie('wx-canvas')
    this.getCates()
    this.getList()
  }

  componentDidShow() {

    const {statusHeight, navHeight} = getNavSize()
    this.setState({
      navHeight: statusHeight + navHeight
    }, () => {
      Taro.nextTick(() => {
        //   // home-top
        //   Taro.createSelectorQuery().in(this.$scope).select('#home-top').boundingClientRect(homeTopRect => {
        //     Taro.createSelectorQuery().in(this.$scope).select('#home-tabs').boundingClientRect(rect => {
        //       //获取元素1距离页面顶部高度
        //         let fixedTop = rect?rect.top + 100:0
        //         let realHeight = homeTopRect.height + this.state.navHeight + 100
        //         this.setState({
        //           isfixed:fixedTop<=realHeight?true:false
        //         },()=>{
        //           // console.log('realHeight', realHeight)
        //           // console.log('isfixed', this.state.isfixed)
        //         })
        //     }).exec()
        //   }).exec()
        Taro.createSelectorQuery().in(this.$scope).select('#home-page').boundingClientRect(rect => { //获取元素1距离页面顶部高度
          console.log('页面出现', rect)
        }).exec()
      })
    })
  }

  componentWillUnmount() {
  }

  componentDidHide() {
  }


  jumpBySWiper(item) {
    const id = item.id
    const name = item.name
    Taro.navigateTo({
      url: `/pages/detail/index?id=${id}&name=${name}`
    })
  }

  seeDetail(item) {
    const id = item.id
    const name = item.name
    Taro.navigateTo({
      url: `/pages/detail/index?id=${id}&name=${name}`
    })
  }

  jump(item) {
    const id = item.id
    const name = item.name
    Taro.navigateTo({
      url: `/pages/detail/index?id=${id}&name=${name}`
    })
  }

  copy(text) {
    Taro.setClipboardData({
      data: text,
      success: (res) => {
        Taro.showToast({
          title: '复制成功',
        });
      }
    })
  }

  chooseCate(item) {
    let {categories} = this.state
    let index = categories.findIndex(e => e.id == item.id)
    if (categories[index].active) {
      return;
    }
    let arr = categories.map((data, idx) => {
      data.active = idx === index
      return data
    })
    this.setState({
      scrollIntoView: this.state.scrollIntoView == 'top' ? 'top1' : 'top'
    })
    this.setState({
      categories: arr,
      cateIds: arr[index].id,
    }, () => {
      Taro.showLoading({
        title: '',
        mask: true
      })
      page = 1
      fetchState = 'init'
      this.props.dispatchNewArrival({
        page,
        size: 20,
        banner: 0,
        order: 'createTime',
        sort: 'desc',
        cateIds: this.state.cateIds,
        status: 1
      }).then(_ => {
        Taro.nextTick(() => {
          Taro.hideLoading()
        })
      })
    })
  }

  getList() {
    this.setState({
      loading: true
    })
    const {cateIds} = this.state
    page = 1
    fetchState = 'init'
    Promise.all([
      this.props.dispatchBanners(),
      this.props.dispatchNewArrival({
        page: 1,
        size: 20,
        banner: 0,
        order: 'createTime',
        sort: 'desc',
        cateIds,
        status: 1
      })
    ]).then(_ => {
      this.setState({loading: false, isfixed: false})
      this.props.onFinishPullDown()
    })
  }

  seeMore() {
    let activeCateItem = this.state.categories.find(item => item.active === true)
    Taro.navigateTo({
      url: '/pages/list/index?cateIds=' + activeCateItem.id + '&name=' + activeCateItem.name
    })
  }

  seeRecommand() {
    Taro.navigateTo({
      url: '/pages/list/index?isRecommend=1&name=浏览量降序排列'
    })
  }

  pageScroll(e) {
    let isfixed = false
    if (!e) return;
    if (!e.detail) return;
    if (e.detail.scrollTop == 0 && this.state.isfixed) {
      isfixed = false;
      this.setState({isfixed}, () => {
        this.props.isfixedChange(isfixed)
      });
      return
    }
    if (e.detail.scrollTop < 0) return;
    Taro.createSelectorQuery().in(this.$scope).select('#home-top').boundingClientRect(homeTopRect => {
      if (homeTopRect.height + this.state.navHeight + 100 <= 0) return;
      if (parseInt(e.detail.scrollTop) + this.state.navHeight >= parseInt(homeTopRect.height + this.state.navHeight + 150)) isfixed = true
      else isfixed = false;
      this.setState({isfixed}, () => {
        this.props.isfixedChange(isfixed)
      });
    }).exec()

  }


  startLoding() {
    this.setState({loading: true})
  }

  render() {
    // homeHeight
    const {loading, month, day, week, navHeight, categories, isfixed, tabHeight, scrollIntoView} = this.state
    const {banners, newArrival, topHeight} = this.props
    return (
      <ScrollView className="home-page" id="home-page"
                  scrollIntoView={scrollIntoView}
                  scrollY={true} onScroll={this.pageScroll.bind(this)}>
        {/* <Navbar type="define"> */}
        {/* <AtNoticebar icon='volume-plus' marquee speed={60} className="qian_noticebar">
                        <Text selectable={false} onLongPress={this.copy.bind(this,'qq95476020')}>
                        小店微信:qq95476020,长按复制微信号
                        </Text>
                    </AtNoticebar>  */}
        {/* <Menu></Menu>
                </Navbar> */}
        <Text id="top2" style={{height: '0', opacity: '0'}}></Text>
        {
          loading && <i-spin size="large" fix fullscreen></i-spin>
        }
        <Fix>
          {/* <Canvas type="2d" id="wx-canvas" style={{'width':'40px',height:'40px'}}></Canvas> */}
          {/* <Canvas id="wx-canvas" canvasId="wx-canvas" disableScroll={true}></Canvas> */}

        </Fix>
        {
          navHeight > 0 && <add-tips navHeight={navHeight}></add-tips>
        }
        {/* <Lottie></Lottie> */}
        {/* <lottie id="lottie" path="http://qamjze7eb.bkt.clouddn.com/lottie.json" width="200" height="200"/> */}
        <View id="home-top">
          <MySwiper imgUrls={banners} onClickImage={this.jumpBySWiper.bind(this)}/>
          <View className="home_wrapper">
            <View className='home_time_title'>
              <Text className="home_time" decode={true}>
                {day}&nbsp;{month}&nbsp;{week}
              </Text>
              <View className="home_time_more">
                {/* 广场 */}
              </View>
            </View>
            <View className='home_time_content'>
              <View className="home_time_content_item home_time_content_item1" onClick={this.seeRecommand.bind(this)}>
                每日推荐
              </View>
              <View className="home_time_content_item home_time_content_item2" onClick={this.seeShoucang.bind(this)}>
                我的收藏
              </View>
            </View>
            <Text id="top" style={{height: '0', opacity: '0'}}></Text>
            <Text id="top1" style={{height: '0', opacity: '0'}}></Text>
          </View>
        </View>
        <View className="home_wrapper">
          <View className={isfixed ? 'home_sticky_wrapper' : 'home_relative_wrapper'}
                style={isfixed ? {top: topHeight + 'px'} : {}} id="home-tabs">
            <View className='home_new_title'>
              <View className="home_new" decode={true}>
                新品上架
              </View>
              <View className="home_new_more" onClick={this.seeMore.bind(this)}>
                更多
              </View>
            </View>
            {/* <View className={isfixed?'home_sticky_wrapper':''} > */}
            <ScrollView
              className={classNames('recommend_box_tab')}
              scrollX={true}>
              {
                categories.map((item, index) => (
                  <View key={item.id}
                        className={classNames('recommend_box_tab_tag', {'recommend_box_tab_tag_active': item.active})}
                        onClick={this.chooseCate.bind(this, item)}
                  >
                    {item.name}
                  </View>
                ))
              }
            </ScrollView>
          </View>
          <ScrollView className={classNames('home_product_content')}
                      style={isfixed ? {marginTop: tabHeight + 'px'} : {}}
                      scrollY={false}
                      scrollX={false}>
            {/* style={isfixed?
                          {
                            marginTop: tabHeight + topHeight + 12 + 'px',
                          height: homeHeight - tabHeight - topHeight - 12 + 'px'
                          }:{}
                        } */}
            {/* style={isfixed?{marginTop: tabHeight + 'px'}:{}} */}
            {
              newArrival.map(item => (
                <View className="home_product_content_item" key={item.id} onClick={this.seeDetail.bind(this, item)}>
                  <View className="home_product_content_item_left">
                    <Image mode="aspectFill" src={item.bannerImage.url} className="home_product_content_item_avator"
                           lazyLoad={true} webp></Image>
                  </View>
                  <View className="home_product_content_item_right">
                    <Text className="home_product_content_item-title" decode={true}>{item.name}</Text>
                    <Text className="home_product_content_item-desc"
                          decode={true}>{item.summary.replace(reg1, '').replace(reg2, '')}</Text>

                    <View className="home_product_content_item_time">
                      <Text className="day">{formatZero(new Date(strToDate(item.createTime)).getDate(), 2)}</Text>/<Text
                      className="month">{formatZero(new Date(strToDate(item.createTime)).getMonth() + 1, 2)}月</Text>
                    </View>
                    <View className="home_product_content_item_like">
                      <Text
                        className={classNames('like-icon', 'at-icon', {'at-icon-heart-2': item.like}, {'at-icon-heart': !item.like})}
                        style={{'color': item.like ? 'red' : 'rgb(34, 34, 34)'}}
                      ></Text>
                    </View>

                  </View>
                </View>
              ))
            }
          </ScrollView>
        </View>
        {/* </View> */}
      </ScrollView>
    )
  }

}

export default Home
